package com.liuweiheng.cloud.util;

import javax.naming.Context;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.util.*;

/**
 * LDAP工具类
 * @author lwh
 * @since 2021/9/9
 */
public class LdapUtil {

    private static String url = "ldap://192.168.0.211:389/";
    private static String baseDn = "OU=广发证券股份有限公司,DC=gfmail,DC=com";
    private static String factory = "com.sun.jndi.ldap.LdapCtxFactory";
    private static String root = "CN=Administrator,CN=Users,DC=gfmail,DC=com";
    private static String simple = "simple";
    private static String pwd = "Ourway@2021!1";

    public static void readLdap() {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY,factory);
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.SECURITY_AUTHENTICATION, simple);
        env.put(Context.SECURITY_PRINCIPAL, root);
        env.put(Context.SECURITY_CREDENTIALS, pwd);
        LdapContext ctx = null;
        Control[] connCtls = null;
        try {
            ctx = new InitialLdapContext(env, connCtls);
            System.out.println( "认证成功" );
        }catch (javax.naming.AuthenticationException e) {
            System.out.println("认证失败：");
            e.printStackTrace();
            return;
        } catch (Exception e) {
            System.out.println("认证出错：");
            e.printStackTrace();
            return;
        }
        List<Map<String, Object>> lm = new ArrayList<Map<String, Object>>();

        try {
            String[] attrPersonArray = { "uid", "userPassword", "displayName", "cn", "sn", "mail", "description" };
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(2);
            searchControls.setReturningAttributes(attrPersonArray);
            //1.要搜索的上下文或对象的名称；2.过滤条件，可为null，默认搜索所有信息；3.搜索控件，可为null，使用默认的搜索控件
            NamingEnumeration<?> contentsEnum = ctx.list(baseDn);
            while (contentsEnum.hasMore()) {
                NameClassPair ncp = (NameClassPair) contentsEnum.next();
                String ncpName = ncp.getName();
                Attributes atts = ctx.getAttributes(ncpName + "," + baseDn, attrPersonArray);
                Attribute objectClassAuttribute = atts.get("objectClass");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

}
